﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Caliburn.Micro;

namespace Caliburn.Micro
{
    public class PageBase : Page 
    {

        public PageBase()
        {
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            this.NavigationService_Navigated();
            base.OnNavigatedTo(e);
        }


        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);
            NavigatingFrom(e);
        }

        private void NavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            var fe = this as FrameworkElement;
            if (fe == null)
                return;

            var guard = fe.DataContext as IGuardClose;
            if (guard != null && !e.Uri.IsAbsoluteUri)
            {
                bool shouldCancel = false;
                guard.CanClose(result =>
                {
                    shouldCancel = !result;
                });

                if (shouldCancel)
                {
                    e.Cancel = true;
                    return;
                }
            }

            var deactivator = fe.DataContext as IDeactivate;
            if (deactivator != null)
                deactivator.Deactivate(e.Uri.IsAbsoluteUri);
        }

        void NavigationService_Navigated()
        {
            if (IsDataContextInitialized)
                return;

            var viewModel = ViewModelLocator.LocateForView(this);

            ViewModelBinder.Bind(viewModel, this, null);

            var activator = viewModel as IActivate;
            if (activator != null)
                activator.Activate();
                        
        }   

        bool _isDataContextInitialized;

        public bool IsDataContextInitialized
        {
            get { return _isDataContextInitialized; }
            set { _isDataContextInitialized = value; }
        }

        

    }
}
